<template>
    <el-dialog v-model="visible" :title="dialogTitle" width="420px" :close-on-click-modal="false" custom-class="login-dialog">
        <!-- 登录表单 -->
        <el-form v-if="currentView === 'login'" ref="loginFormRef" :model="loginForm" :rules="loginRules" label-width="0">
            <div class="form-header">
                <div class="form-title">欢迎回来</div>
                <div class="form-subtitle">请登录您的账号继续使用</div>
            </div>

            <el-form-item prop="phone_num">
                <el-input v-model="loginForm.phone_num" placeholder="请输入手机号" size="large" autocomplete="off">
                    <template #prefix>
                        <el-icon>
                            <User />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password size="large" autocomplete="new-password">
                    <template #prefix>
                        <el-icon>
                            <Lock />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <div class="form-actions">
                <el-link  @click="currentView = 'forgot'" class="text-btn">忘记密码？</el-link>
                <el-link  @click="currentView = 'register'" class="text-btn">注册账号</el-link>
            </div>
            <el-button type="primary" class="submit-btn" :loading="loading" @click="handleLogin">
                登录
            </el-button>
        </el-form>

        <!-- 注册表单 -->
        <el-form v-if="currentView === 'register'" ref="registerFormRef" :model="registerForm" :rules="registerRules" label-width="0" autocomplete="off">
            <div class="form-header">
                <div class="form-title">创建账号</div>
                <div class="form-subtitle">填写信息完成注册</div>
            </div>

            <el-form-item prop="phone_num">
                <el-input v-model="registerForm.phone_num" placeholder="请输入手机号" size="large">
                    <template #prefix>
                        <el-icon>
                            <User />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>

            <el-form-item prop="password">
                <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" show-password size="large" autocomplete="new-password">
                    <template #prefix>
                        <el-icon>
                            <Lock />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item prop="confirmPassword">
                <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请确认密码" show-password size="large" autocomplete="new-password">
                    <template #prefix>
                        <el-icon>
                            <Lock />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item prop="verify_code" class="verify-code-item">
                <el-input v-model="registerForm.verify_code" placeholder="请输入验证码" size="large" autocomplete="one-time-codes">
                    <template #prefix>
                        <el-icon>
                            <Key />
                        </el-icon>
                    </template>
                </el-input>
                <el-button :disabled="cooldown > 0" @click="handleSendCode('register')" class="code-btn" :class="{'btn-cooldown': cooldown > 0}">
                    {{ cooldown > 0 ? `${cooldown}s` : '获取验证码' }}
                </el-button>
            </el-form-item>
            <el-form-item prop="nick_name">
                <el-input v-model="registerForm.nick_name" placeholder="请输入昵称" size="large">
                    <template #prefix>
                        <el-icon>
                            <User />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item prop="email">
                <el-input v-model="registerForm.email" placeholder="请输入邮箱" size="large">
                    <template #prefix>
                        <el-icon>
                            <Message />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>

            <div class="form-actions center">
                <el-link  @click="currentView = 'login'" class="text-btn">返回登录</el-link>
            </div>
            <el-button type="primary" class="submit-btn" :loading="loading" @click="handleRegister">
                注册
            </el-button>
        </el-form>

        <!-- 忘记密码表单 -->
        <el-form v-if="currentView === 'forgot'" ref="forgotFormRef" :model="forgotForm" :rules="forgotRules" label-width="0">
            <div class="form-header">
                <div class="form-title">重置密码</div>
                <div class="form-subtitle">我们将向您的手机发送验证码</div>
            </div>

            <el-form-item prop="phone_num">
                <el-input v-model="forgotForm.phone_num" placeholder="请输入手机号" size="large">
                    <template #prefix>
                        <el-icon>
                            <Message />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item prop="verify_code" class="verify-code-item">
                <el-input v-model="forgotForm.verify_code" placeholder="请输入验证码" size="large" autocomplete="new-code">
                    <template #prefix>
                        <el-icon>
                            <Key />
                        </el-icon>
                    </template>
                </el-input>
                <el-button :disabled="cooldown > 0" @click="handleSendCode('forgot')" class="code-btn" :class="{'btn-cooldown': cooldown > 0}">
                    {{ cooldown > 0 ? `${cooldown}s` : '获取验证码' }}
                </el-button>
            </el-form-item>
            <el-form-item prop="password">
                <el-input v-model="forgotForm.password" type="password" placeholder="请输入新密码" show-password size="large" autocomplete="new-password">
                    <template #prefix>
                        <el-icon>
                            <Lock />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <div class="form-actions center">
                <el-link  @click="currentView = 'login'" class="text-btn">返回登录</el-link>
            </div>
            <el-button type="primary" class="submit-btn" :loading="loading" @click="handleResetPassword">
                重置密码
            </el-button>
        </el-form>
    </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue'
import { User, Lock, Message, Key } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { login, register, resetPassword, sendVerifyCode, send_message } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const props = defineProps({
    modelValue:  {
        type: [Boolean,],
        default: ''
    }, 
})

const emit = defineEmits(['update:modelValue', 'login-success'])

// 对话框可见性
const visible = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
})

// 当前视图（login/register/forgot）
const currentView = ref('login')
const loading = ref(false)
const cooldown = ref(0)

// 对话框标题
const dialogTitle = computed(() => {
    switch (currentView.value) {
        case 'register': return '注册账号'
        case 'forgot': return '重置密码'
        default: return '账号登录'
    }
})

// 登录表单
const loginFormRef = ref(null)
const loginForm = ref({
    phone_num: '',
    password: ''
})

// 注册表单
const registerFormRef = ref(null)
const registerForm = ref({
    phone_num: '',
    password: '',
    confirmPassword: '',
    nick_name: '',
    email: '',
    verify_code: ''
})

// 忘记密码表单
const forgotFormRef = ref(null)
const forgotForm = ref({
    phone_num: '',
    verify_code: '',
    password: ''
})

// 表单验证规则
const loginRules = {
    phone_num: [
        { required: true, message: "手机号码不能为空", trigger: "blur" },
        { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
    ],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const registerRules = {
    phone_num: [
        { required: true, message: "手机号码不能为空", trigger: "blur" },
        { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
    ],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== registerForm.value.password) {
                    callback(new Error('两次输入的密码不一致'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    nick_name: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    // verify_code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

const forgotRules = {
    phone_num: [
        { required: true, message: "手机号码不能为空", trigger: "blur" },
        { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
    ],
    verify_code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
    password: [{ required: true, message: '请输入新密码', trigger: 'blur' }]
}

// 发送验证码
const handleSendCode = async (type) => {
    const phone_num = type === 'register' ? registerForm.value.phone_num : forgotForm.value.phone_num
    if (!phone_num) {
        ElMessage.warning('请先输入手机号')
        return
    }

    try {
        await send_message({ phone_num, type: type === 'register' ? 'register_user' : 'forget_pass' })
        ElMessage.success('验证码已发送')
        cooldown.value = 60
        const timer = setInterval(() => {
            cooldown.value--
            if (cooldown.value <= 0) {
                clearInterval(timer)
            }
        }, 1000)
    } catch (error) {
        // console.error('发送验证码失败:', error)
    }
}

// 登录
const handleLogin = async () => {
    if (!loginFormRef.value) return
    await loginFormRef.value.validate(async (valid) => {
        if (valid) {
            loading.value = true
            try {
                const response = await login(loginForm.value)
                emit('login-success', response.data)
                visible.value = false
                // 清空登录表单
                loginFormRef.value.resetFields()
            } catch (error) {
                // console.error('登录失败:', error)
            } finally {
                loading.value = false
            }
        }
    })
}

// 注册
const handleRegister = () => {
    registerFormRef.value.validate(async (valid) => {
        if (!valid) return

        loading.value = true
        try {
            await register(registerForm.value)
            ElMessage.success('注册成功')
            currentView.value = 'login'
            // 清空注册表单
            registerFormRef.value.resetFields()
            // 重置验证码倒计时
            cooldown.value = 0
        } catch (error) {
            // console.error('注册失败:', error)
        } finally {
            loading.value = false
        }
    })
}

// 重置密码
const handleResetPassword = () => {
    forgotFormRef.value.validate(async (valid) => {
        if (!valid) return

        loading.value = true
        try {
            await resetPassword(forgotForm.value)
            ElMessage.success('密码重置成功')
            currentView.value = 'login'
            // 清空重置密码表单
            forgotFormRef.value.resetFields()
            // 重置验证码倒计时
            cooldown.value = 0
        } catch (error) {
            // console.error('重置密码失败:', error)
        } finally {
            loading.value = false
        }
    })
}
</script>

<style lang="scss" scoped>
// 全局对话框样式
:deep(.login-dialog) {
    border-radius: 12px;
    overflow: hidden;

    .el-dialog__header {
        margin: 0;
        padding: 20px 20px 0;
        text-align: center;

        .el-dialog__title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
        }
    }

    .el-dialog__body {
        padding: 20px 30px 30px;
    }
}

// 表单头部样式
.form-header {
    text-align: center;
    margin-bottom: 24px;

    .form-title {
        font-size: 22px;
        font-weight: 600;
        color: #333;
        margin-bottom: 8px;
    }

    .form-subtitle {
        font-size: 14px;
        color: #909399;
    }
}

// 表单项样式
:deep(.el-form-item) {
    margin-bottom: 20px;

    .el-input__wrapper {
        padding: 0 15px;
        border-radius: 8px;
        box-shadow: 0 0 0 1px #dcdfe6;
        transition: all 0.3s;

        &:hover,
        &.is-focus {
            box-shadow: 0 0 0 1px #6751f0;
        }
    }

    .el-input__inner {
        height: 44px;
    }

    .el-input__prefix {
        color: #909399;
        font-size: 16px;
        margin-right: 10px;
    }
}

// 操作按钮样式
.form-actions {
    display: flex;
    justify-content: space-between;
    margin-bottom: 24px;

    &.center {
        justify-content: center;
    }

    .text-btn {
        padding: 0;
        font-size: 14px;
        color: #6751f0;

        // &:hover {
        //     color: #5240d0;
        //     text-decoration: underline;
        // }
    }
}

// 提交按钮样式
.submit-btn {
    width: 100%;
    height: 44px;
    font-size: 16px;
    border-radius: 8px;
    background: #6751f0;
    border-color: #6751f0;
    transition: all 0.3s;

    &:hover {
        background: #5240d0;
        border-color: #5240d0;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(103, 81, 240, 0.3);
    }

    &:active {
        transform: translateY(0);
    }
}

// 验证码输入框样式
.verify-code-item {
    display: flex;
    gap: 10px;

    :deep(.el-form-item__content) {
        display: flex;
        gap: 10px;
    }

    .el-input {
        flex: 1;
    }

    .code-btn {
        width: 120px;
        height: 44px;
        border-radius: 8px;
        font-size: 14px;
        border: 1px solid #6751f0;
        color: #6751f0;
        transition: all 0.3s;

        &:hover:not(.btn-cooldown) {
            background-color: rgba(103, 81, 240, 0.1);
        }

        &.btn-cooldown {
            background-color: #f5f7fa;
            border-color: #dcdfe6;
            color: #909399;
        }
    }
}

// 添加动画效果
.el-form {
    animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}
</style> 